package com.parking.action;

import com.parking.bean.ParkSpace;
import com.parking.service.ParkSpaceService;
import com.parking.service.impl.ParkSpaceServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/parkSpace")
public class ParkSpaceServlet extends HttpServlet {
    private ParkSpaceService parkSpaceService=new ParkSpaceServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String method =request.getParameter("method");
        switch(method){
            case "list":
                request.setAttribute("list",this.parkSpaceService.list());
                request.getRequestDispatcher("parkspacemanager.jsp").forward(request,response);
                break;
            case "search":
                String key=request.getParameter("key");
                String value=request.getParameter("value");
                request.setAttribute("list",this.parkSpaceService.search(key,value));
                request.getRequestDispatcher("parkspacemanager.jsp").forward(request,response);
                break;
            case "save":
                String local=request.getParameter("local");
                String parkSpaceId=request.getParameter("parkSpaceId");
                this.parkSpaceService.save(new ParkSpace(parkSpaceId,local));
                response.sendRedirect("/parkSpace?method=list");
                break;
            case "update":
                String idStr=request.getParameter("id");
                Integer id =Integer.parseInt(idStr);
                parkSpaceId=request.getParameter("parkSpaceId");
                local=request.getParameter("local");
                String parkSpaceState=request.getParameter("parkSpaceState");
                this.parkSpaceService.update(new ParkSpace(id,parkSpaceId,local,parkSpaceState));
                response.sendRedirect("/parkSpace?method=list");
                break;
            case "delete":
                idStr=request.getParameter("id");
                id=Integer.parseInt(idStr);
                this.parkSpaceService.delete(id);
                response.sendRedirect("/parkSpace?method=list");
                break;

        }
    }
}
